import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * Semaphore控制同时多少个线程并发执行,没有拿到灯的等待
 */
public class SemaPhoreTest {

	public static void main(String[] args) {
		ExecutorService executorService = Executors.newCachedThreadPool();
		/**
		 * Semaphore 第一个参数 是灯的个数  第二个参数是是否fair先到先得
		 */
		final Semaphore semaphore = new Semaphore(3, true);
		
		final Businiss businiss = new Businiss(semaphore);
		
		for(int i=0;i<10;i++){
			executorService.execute(new Runnable(){
				public void run() {
					businiss.doSomthing();
				}
			});
		}
	}
	
	static class Businiss {
		
		private Semaphore semaphore;
		
		public Businiss(Semaphore semaphore){
			this.semaphore = semaphore;
		}
		
		public void doSomthing(){
			try {
				semaphore.acquire();//获得一个灯
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			
			System.out.println("线程:"+Thread.currentThread().getName() +
					" 进入,已有 ：" + (3 - semaphore.availablePermits())+ 
					" 个线程并发.");
			try {
				Thread.sleep((long)Math.random()*10000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
				
			System.out.println("线程:" + Thread.currentThread().getName() + " 马上离开.");
		
			semaphore.release();
			//下面代码有时候执行不准确，因为其没有和上面的代码合成原子单元
			System.out.println("线程:"+Thread.currentThread().getName() +
					" 已离开,已有 ：" + (3 - semaphore.availablePermits())+ 
					" 个线程并发.");
			
		}
		
	}

}
